// ex8_8_4.cpp
#include <cstddef>
#include <cstdlib>
#include <iostream>
#include <cstring>        // for strlen(), strcpy()
struct stringy
{
    char *str;            // points to a string
    int ct;               // length of a string (not counting '\0')
};
// prototypes for set(), show(), and show() go here
void set(struct stringy &, const char *str);
//void show(struct stringy &);
void show(struct stringy &, int = 0);   
void show(const char *str, int = 0);
//void show(const char *str, int);   
int main(void)
{
	stringy beany;
	char testing[] = "Reality isn't what it used to be.";
	set(beany, testing);    // first argument is a reference,
                // allocates space to hold copy of testing,
                // sets str member of beany to point to the
                // new block, copies testing to new block,
                // and sets ct member of beany
    show(beany);        // prints member string once
    show(beany, 2);     // prints member stringy twice
    testing[0] = 'D';
    testing[1] = 'u';
    show(testing);    // prints testing string once;
    show(testing, 3);    // prints testing string thrice
    show("Done!");                         
    return 0;
}

void set(struct stringy &sy, const char *str)
{   //char *ptr = new char[strlen(str)];
    sy.str = new char[strlen(str)]; 
    if (sy.str == nullptr)
    {
        std::cerr << "allocate stringy.str memory failed" << std::endl;
        exit(EXIT_FAILURE);
    }    
    strncpy(sy.str, str, strlen(str));
    sy.ct = strlen(str);
}

// void show(struct stringy &sy)
// {
//     cout << sy.str << " " << sy.ct << "\n";
// }

// void show(struct stringy &sy, int n)
// {
//     while (n-- > 0)
//     {
//         cout << sy.str << " " << sy.ct << "\n";
//     }
// }  
void show(struct stringy &sy, int n)
{
    if (n > 0)
    {
        while (n-- > 0)
        {
            std::cout << sy.str << " " << sy.ct << "\n";
        }
    }
    else 
        std::cout << sy.str << " " << sy.ct << "\n";

}
// void show(const char *str)
// {
//     cout << str << "\n";
// }

// void show(const char *str, int n)
// {
//     while (n-- > 0)
//     {
//         cout << str << "\n";
//     }
// }
void show(const char *str, int n)
{
    if (n > 0)
    {
        while (n-- > 0)
        {
            std::cout << str << "\n";
        }
    }
    else 
        std::cout << str << "\n";
}